﻿using System;
using System.Diagnostics;

namespace Utilities
{
    /// <summary>
    /// Log type.
    /// </summary>
    public enum LogType
    {
        None,
        Verbose,
        Info,
        Error,
    }

    /// <summary>
    /// Singleton logger.
    /// </summary>
    public class Logger
    {
        #region Singleton
        private static volatile Logger m_instance;
        private static object m_mutex = new Object();

        private Logger() { }

        public static Logger Instance
        {
            get
            {
                if (m_instance == null)
                {
                    lock (m_mutex)
                    {
                        if (m_instance == null)
                            m_instance = new Logger();
                    }
                }

                return m_instance;
            }
        }
        #endregion

        #region Privates
        /// <summary>
        /// Gets the class which called the logger.
        /// </summary>
        /// <returns>Class's name</returns>
        private string getCallingClass()
        {
            StackTrace st = new StackTrace();
            int frame = 1;
            Type tempType;
            do
            {
                tempType = st.GetFrame(frame).GetMethod().DeclaringType;
                frame++;
            } while (tempType == typeof(Logger));
            return tempType.FullName;
        }
        #endregion

        #region Methods

        /// <summary>
        /// Logs an Info message
        /// </summary>
        /// <param name="format"></param>
        /// <param name="args"></param>
        public void Log(string format, params object[] args)
        {
            Log(format, ConsoleColor.Green, LogType.Info, args);
        }

        /// <summary>
        /// Logs a message
        /// </summary>
        /// <param name="format"></param>
        /// <param name="color">Color to use</param>
        /// <param name="type">Type of the log</param>
        /// <param name="args"></param>
        public void Log(string format, ConsoleColor color, LogType type,  params object[] args)
        {

            string callingClassName = getCallingClass();
            string header = string.Format("[{0}][{1}] ", type.ToString(), callingClassName);
            string output = header + string.Format(format, args);
#if DEBUG
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(output);
#endif
        }

        /// <summary>
        /// Logs an error message
        /// </summary>
        /// <param name="format"></param>
        /// <param name="args"></param>
        public void LogError(string format, params object[] args)
        {
            Log(format, ConsoleColor.Red, LogType.Error, args);
        }
        #endregion
    }
}
